import 'package:winkai/generated/json/base/json_convert_content.dart';
import 'package:get/get.dart';

class BaseResult<T> {
  BaseResult(this.code, this._message, this.data);

  BaseResult.fromJson(Map<String, dynamic> json, {T? dataInstance}) {
    code = (json['code'] is int) ? (json['code']) : -1;
    _message = (json['item'] is String) ? json['item'] as String : null;
    _error = (json['error'] is String) ? json['error'] as String : null;
    if (json.containsKey('data')) {
      data =
          _generateOBJ<T>(json['data'] as Object?, dataInstance: dataInstance);
    }
  }

  BaseResult.fromJsonNoBody(Object? json, {T? dataInstance}) {
    code = 0;
    _message = null;
    _error = null;
    data = _generateOBJ<T>(json, dataInstance: dataInstance);
  }

  bool get isSucceed =>
      code == 0 || (_message ?? '').toLowerCase() == 'success';

  int? code;
  String? _message;
  T? data;
  String? _error;

  String get message => (_message ?? _error ?? '').tr;

  String get error => (_error ?? _message ?? '').tr;

  T? _generateOBJ<O>(Object? json, {T? dataInstance}) {
    if (json == null) return null;
    var className = T.toString();
    if (className == 'String') {
      return json.toString() as T;
    } else if (className == 'Map<dynamic, dynamic>' ||
        className == 'Map<String, dynamic>') {
      return json as T;
    } else if (className == 'List<dynamic>' && json is List) {
      return json as T;
    } else if (className == 'List<String>' && json is List) {
      List<String> list = [];
      for (var value in json) {
        if (value is String) {
          list.add(value);
        }
      }
      return list as T;
    } else {
      return JsonConvert.fromJsonAsT<T>(json);
    }
  }
}
